package com.hzw.saas.common.security.utils;


import com.hzw.saas.common.config.exception.DefaultSaasException;
import com.hzw.saas.common.security.pojo.dto.SaasUser;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import lombok.experimental.UtilityClass;

/**
 * 安全工具类
 *
 * @author L.cm
 */
@UtilityClass
public class SecurityUtils {

	/**
	 * 获取Authentication
	 */
	public Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw DefaultSaasException.build("未登录").status(HttpStatus.UNAUTHORIZED);
        }
        return authentication;
	}

	/**
	 * 获取用户
	 */
	public SaasUser getUser() {
		Authentication authentication = getAuthentication();
		Object principal = authentication.getPrincipal();
        if (principal instanceof SaasUser) {
			return (SaasUser) principal;
		}
		throw DefaultSaasException.build("未登录").status(HttpStatus.UNAUTHORIZED);
	}

    public String getUserId() {
        return getUser().getUserId();
    }

    public OAuth2AuthenticationDetails getAuthDetails() {
        Authentication authentication = getAuthentication();
        Object details = authentication.getDetails();
        if (details instanceof OAuth2AuthenticationDetails) {
            return (OAuth2AuthenticationDetails) details;
        }
        throw DefaultSaasException.build("未登录").status(HttpStatus.UNAUTHORIZED);
    }

}
